import java.util.logging.Logger;
import com.google.appengine.api.datastore.*
import static com.google.appengine.api.datastore.FetchOptions.Builder.*

Logger log = Logger.getLogger('SessionsController');


if(params?.index ==~ /(?i)true/)
{
	index()
}
if(params?.delete ==~ /(?i)true/)
{
	delete()
}
if(params?.ping ==~ /(?i)true/)
{
	ping()
}

private void index()
{
	def query = new Query("_ah_SESSION")
	query.addSort("_expires", Query.SortDirection.ASCENDING)
	PreparedQuery preparedQuery = datastore.prepare(query)
	request['anzahl'] = preparedQuery.countEntities() 
	def entities = preparedQuery.asList( withLimit(1000) )
	request['list'] = entities
	forward '/admin/ahsessions.gtpl'
}
private void delete ()
{
	long counter = 0;
	long t1 = System.currentTimeMillis()
	
	def query = new Query("_ah_SESSION")
	query.addSort("_expires", Query.SortDirection.ASCENDING)
 	PreparedQuery preparedQuery = datastore.prepare(query)
 	def entities = preparedQuery.asList( withLimit(100) )
 	for(i in entities)
 	{
 		//abgelaufen
 		if(i._expires < t1)
 		{
 			i.delete()
 			counter++;
 		}
 	}
	long t2 = System.currentTimeMillis()
	request['del'] = counter
	request['dauer'] = (t2-t1)
	if(counter > 0)
		log.info("Gelöschte Sessions: "+counter+', Dauer: '+(t2-t1))
	index()
}
private void ping()
{
	forward '/admin/ping.gtpl'
}